﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using UIShell.OSGi;
using Pasys.PresentationCore;
using Pasys.PresentationCore.DockShell;

namespace WinFormShell
{
    public partial class RootForm : Form, ILayoutViewProxyContainer
    {

        private ShellDockLayoutView layoutView;
        public IShellLayoutViewProxy LayoutViewProxy
        {
            get
            {
                return layoutView.LayoutViewProxy;
            }
        }
        public string SessionKey
        {
            get
            {
                if (layoutView.LayoutViewProxy != null)
                {
                    return layoutView.LayoutViewProxy.SessionKey;
                }
                else
                {
                    return string.Empty;
                }
            }
        }

        public IWorkspace Workspace
        {
            get { return layoutView.Workspace; }
        }

        public RootForm()
        {
            InitializeComponent();
            var commandBus = BundleRuntime.Instance.GetFirstOrDefaultService<ICommandBusService>();
            commandBus.SubscribeCommandEvent(CommandNames.Quit, Quit);

        }

        public void ShowLayoutIvew(ShellDockLayoutView view)
        {
            layoutView = view;
            Controls.Clear();
            Controls.Add(view);
            view.Dock = DockStyle.Fill;
        }


        public void Quit(object sender, object e)
        {
            this.Close();
        }

        private void RootForm_Activated(object sender, EventArgs e)
        {
            RegistProxyContainer();
        }

        private void RegistProxyContainer()
        {
            var List = BundleRuntime.Instance.GetService<ILayoutViewProxyContainer>();
            for (int i = List.Count - 1; i >= 0; i--)
            {
                BundleRuntime.Instance.RemoveService<ILayoutViewProxyContainer>(List[i]);
            }
            var con = BundleRuntime.Instance.GetFirstOrDefaultService<ILayoutViewProxyContainer>();
            if (con != null)
            {
                BundleRuntime.Instance.RemoveService<ILayoutViewProxyContainer>(con);
            }
            BundleRuntime.Instance.AddService<ILayoutViewProxyContainer>(this);

            List = BundleRuntime.Instance.GetService<ILayoutViewProxyContainer>();
            if (List.Count != 1)
            {
                throw new Exception();
            }
        }

        private void RootForm_Load(object sender, EventArgs e)
        {
            RegistProxyContainer();
        }

    }
}
